package com.th.atguigu;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @author ThreePure
 * @date 2022/3/9 21:20
 * @description: 通过JDK动态代理实现功能增强
 * @since 1.8
 */
public class JDKProxy {
    public static void main(String[] args) {
        Class[] interfaces = {UserDao.class};
        UserDaoImpl userDao = new UserDaoImpl();
        //创建接口实现类的接口对象
        UserDao proxyDao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int addResult = proxyDao.add(1, 2);
        System.out.println("add method result:"+addResult);
    }
}

/**创建代理对象代码*/
class UserDaoProxy implements InvocationHandler {

    private Object obj;

    /**把创建的是谁的代理对象，就把谁传递过来，通过有参构造传递。比如这里产生的是UserdaoImpl的代理对象。*/
    /**为例让这个代理类使用更加广泛，直接传递Object对象，*/
    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }

    /**增强的逻辑代码*/
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 被增强方法之前
        System.out.println("It was executed before the "+method.getName()+",and the args :"+ Arrays.toString(args));

        // 被增强方法执行
        Object res = method.invoke(obj, args);

        // 被增强方法之后
        System.out.println("It was executed before ... :"+obj.toString());

        return res;
    }
}
